package com.example.appinstalldemo.utils;

import static android.content.Context.ACTIVITY_SERVICE;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author: njb
 * @date: 2023/8/8 0:03
 * @desc:
 */
public class ToolUtils {
    private static final String TAG = ToolUtils.class.getName();

    /**
     * 打开软件
     *
     * @param packageName 包名
     * @param context     上下文对象
     */
    public static void openApp(String packageName, Context context) {
        if (packageName != null) {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            context.startActivity(intent);
        }
    }

    public static void openApp(String packageName, Context context, Bundle bundle) {
        Intent intent = new Intent();
        ComponentName comp = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.SplashActivity");
        intent.setComponent(comp);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    /**
     * 获取前台程序包名
     */
    public static String getForegroundAppPackageName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        return componentInfo.getPackageName();
    }

    /**
     * 根据报名杀死应用
     */
    public static void killApp(Context context, String packageName) {
        try {
            ActivityManager m = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            Method method = m.getClass().getMethod("forceStopPackage", String.class);
            method.setAccessible(true);
            method.invoke(m, packageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 杀死第三方应用
     *
     * @param context
     * @param packageName
     */
    public static void killThirdApp(Context context, String packageName) {
        if (packageName != null) {
            killApp(context, packageName);
        }
    }

    /**
     * 静默安装或升级
     *
     * @param apkAbsolutePath
     * @return
     */
    public static boolean silenceInstallApk(Context context, String apkAbsolutePath) {
        if (apkAbsolutePath.contains("Launcher") || apkAbsolutePath.contains("launcher")) {
//        当在待机页时，后台重启升级launcher后保持待机状态。
//        (在安装apk时判断是launcher，设个true进去，launcher安装完，重启launcher生效)
            MMKVUtils.getInstance().encode("key_reboot", "");
        }
        try {
            Log.d(TAG, "开始安装APK:" + apkAbsolutePath);
            Process su = Runtime.getRuntime().exec("su");
            DataInputStream inputStream = new DataInputStream(su.getInputStream());
            DataOutputStream output = new DataOutputStream(su.getOutputStream());
            output.write(("pm install -r " + apkAbsolutePath).getBytes());
            output.write('\n');
            output.flush();
            String val = "";
            while ((val = inputStream.readLine()) != null) {
                Log.i(TAG, "====安装APK结果： " + val);
                if ("Success".equals(val)) {
                    Log.d(TAG, "安装APK成功:" + apkAbsolutePath);
                    return true;
                } else if (val.contains("FAILED")) {  //安装失败Failure [INSTALL_FAILED_VERSION_DOWNGRADE]
                    String installResult = apkAbsolutePath + "安装失败! " + val;
                    //将安装失败的信息发送到SplashFragment显示
                    //EventBus.getDefault().post(new UpdateAppEvent(false, installResult));
                    return false;
                }
            }
            Log.d(TAG, "安装APK失败:" + apkAbsolutePath);
            return false;
        } catch (Exception e) {
            Log.d(TAG, "安装APK出错:" + apkAbsolutePath);
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取前台activity名称
     *
     * @param context
     * @return
     */
    public static String getForegroundActivityName(Context context) {
        if (context == null) {
            return "";
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            return cpn.getClassName();
        }
        return "";
    }


    /**
     * 判断APP是否安装了
     *
     * @param packageName 包名
     * @return
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        try {
            packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 卸载客房娱乐第三方应用
     *
     * @param context
     */
    public static void unInstallApp(Context context, String packageName) {
        if (packageName == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        packageInstaller.uninstall(packageName, pendingIntent.getIntentSender());
    }

    public static void unInstall(Context context, String packageName) {
        if (packageName == null) {
            return;
        }
        Uri uri = Uri.parse("package:" + packageName);
        Intent uninstall = new Intent(Intent.ACTION_DELETE, uri);
        uninstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(uninstall);
    }
}
